<template>
	<view class="attendance-page">
		<!-- 顶部选择栏 -->
		<view class="top-bar">
			<!-- 班级选择 -->
			<view class="class-section">
				<view @click="showClassPicker = true" class="picker-btn">
					{{ selectedClassLabel || '选择班级' }}
				</view>
				<!-- 课时 -->
				<view class="progress">{{ progressText }}</view>
			</view>

			<u-picker :show="showClassPicker" :columns="classList" keyName="label" @confirm="onClassConfirm"
				@cancel="showClassPicker = false" :defaultIndex="defaultIndex" />



			<image :src="teacherAvatar" class="teacher-avatar" />
		</view>

		<!-- 全勤和提交 -->
		<view class="action-bar">
			<u-checkbox-group v-model="allCheckedArr" @change="handleAllCheck">
				<u-checkbox :name="true" shape="square" size="28"></u-checkbox>

			</u-checkbox-group>
			<view>全勤</view>
			<view @click="showCalendar = true" class="picker-btn">
				{{ selectedDate || '选择日期' }}

				<view class="arrow-up"></view>
			</view>



			<view style="submit-btn">
				<u-button type="error" size="mini" @click="submitAttendance">提交考勤</u-button>
			</view>

			<u-calendar :show="showCalendar" :max-date="maxDate" :min-date="minDate" @confirm="onDateConfirm"
				@close="showCalendar = false" :monthNum="24" />

		</view>

		<!-- 教师考勤列表 -->
		<view class="teacher-list">
			<view class="teacher-item" v-for="(teacher, idx) in teachers" :key="teacher.id">
				<image :src="teacher.avatar" class="avatar" />
				<view class="name">{{ teacher.name }}</view>
				<!-- <view class="tag" v-if="teacher.tag">{{ teacher.tag }}</view> -->
				<view class="status-box">
					<view class="status-row">
						<view class="status-item" :class="{ active: teacher.status === 0 }"
							@click="setStatus(teacher, 0)">出勤</view>
						<view class="status-item" :class="{ active: teacher.status === 1 }"
							@click="setStatus(teacher, 1)">缺勤</view>
					</view>
					<view class="status-row">
						<view class="status-item" :class="{ active: teacher.status === 2 }"
							@click="setStatus(teacher, 2)">请假</view>
						<view class="status-item" :class="{ active: teacher.status === 3 }"
							@click="setStatus(teacher, 3)">调课</view>
					</view>
				</view>

			</view>
		</view>

		<!-- 调课弹窗 -->
		<u-popup :show="showTransferPopup" mode="center" @close="closeTransferPopup">
			<view class="transfer-popup">
				<view class="transfer-header">
					<view class="transfer-title">学生调课</view>
					<view class="transfer-subtitle">请选择调课时间和目标班级</view>
				</view>
				<view class="transfer-form">
					<view class="form-item">
						<view class="form-label">
							<text class="label-icon">👤</text>
							<text>学员姓名</text>
						</view>
						<view class="form-value">{{ currentTeacher.name }}</view>
					</view>
					<view class="form-item">
						<view class="form-label">
							<text class="label-icon">🏫</text>
							<text>所在班级</text>
						</view>
						<view class="form-value">{{ selectedClassLabel }}</view>
					</view>
					<view class="form-item">
						<view class="form-label">
							<text class="label-icon">📅</text>
							<text>调课时间</text>
						</view>
						<view class="picker-btn transfer-picker" @click="showTransferDatePicker = true">
							<text>{{ transferDate || '选择时间' }}</text>
							<text class="picker-arrow">▼</text>
						</view>
					</view>
					<view class="form-item">
						<view class="form-label">
							<text class="label-icon">🎯</text>
							<text>选择班级</text>
						</view>
						<view class="picker-btn transfer-picker" @click="showTransferClassPicker = true">
							<text>{{ transferClassLabel || '选择班级' }}</text>
							<text class="picker-arrow">▼</text>
						</view>
					</view>
					<view class="form-item">
						<view class="form-label">
							<text class="label-icon">📝</text>
							<text>调课备注</text>
						</view>
						<view class="form-input">
							<u-input v-model="transferRemark" type="textarea" placeholder="请输入调课备注（可选）" />
						</view>
					</view>
				</view>
				<view class="transfer-buttons">
					<u-button type="default" @click="closeTransferPopup" class="cancel-btn">取消</u-button>
					<u-button type="primary" @click="submitTransfer" class="submit-btn">确认调课</u-button>
				</view>
			</view>
		</u-popup>

		<!-- 调课时间选择器 -->
		<u-calendar :show="showTransferDatePicker" :max-date="maxDate" :min-date="minDate"
			@confirm="onTransferDateConfirm" @close="showTransferDatePicker = false" />

		<!-- 调课班级选择器 -->
		<u-picker :show="showTransferClassPicker" :columns="transferClassList" keyName="label"
			@confirm="onTransferClassConfirm" @cancel="showTransferClassPicker = false" />
	</view>
</template>

<script>
	import {
		selectClass
	} from '@/api/attend';
	export default {
		data() {
			return {
				userId: 0,
				classList: [
					[{
							label: '绘画A班',
							value: 'A'
						},
						{
							label: '绘画B班',
							value: 'B'
						}
					]
				],
				defaultIndex: [0],
				transferClassList: [
					[{
							label: '美术A班',
							value: 'A'
						},
						{
							label: '美术B班',
							value: 'B'
						}
					]
				],
				selectedClass: '',
				selectedClassLabel: '',
				showClassPicker: false,
				selectedDate: '',
				showCalendar: false,
				minDate: '2025-03-01',
				maxDate: '2025-06-11',
				progressText: '9 / 20 课时',
				teacherAvatar: 'http://1.94.233.8:19000/education-bucket/b8bd6d7d-0d41-484c-9fc7-a6c832b5ec1b.jpg',
				allCheckedArr: [true],
				teachers: [{
						id: 1,
						name: '小红',
						avatar: 'http://1.94.233.8:19000/education-bucket/b8bd6d7d-0d41-484c-9fc7-a6c832b5ec1b.jpg',
						status: 0,
						tag: '调课'
					},
					{
						id: 2,
						name: '小白',
						avatar: 'http://1.94.233.8:19000/education-bucket/b8bd6d7d-0d41-484c-9fc7-a6c832b5ec1b.jpg',
						status: 0,
						tag: '调课'
					},
					{
						id: 3,
						name: '小黑',
						avatar: 'http://1.94.233.8:19000/education-bucket/b8bd6d7d-0d41-484c-9fc7-a6c832b5ec1b.jpg',
						status: 0,
						tag: '调课'
					},
					{
						id: 4,
						name: '小黑',
						avatar: 'http://1.94.233.8:19000/education-bucket/b8bd6d7d-0d41-484c-9fc7-a6c832b5ec1b.jpg',
						status: 0,
						tag: '调课'
					},
					{
						id: 5,
						name: '小黑',
						avatar: 'http://1.94.233.8:19000/education-bucket/b8bd6d7d-0d41-484c-9fc7-a6c832b5ec1b.jpg',
						status: 0,
						tag: '调课'
					},
					{
						id: 6,
						name: '小黑',
						avatar: 'http://1.94.233.8:19000/education-bucket/b8bd6d7d-0d41-484c-9fc7-a6c832b5ec1b.jpg',
						status: 0,
						tag: '调课'
					},
					{
						id: 7,
						name: '小黑',
						avatar: 'http://1.94.233.8:19000/education-bucket/b8bd6d7d-0d41-484c-9fc7-a6c832b5ec1b.jpg',
						status: 0,
						tag: '调课'
					}
				],
				showTransferPopup: false,
				showTransferDatePicker: false,
				showTransferClassPicker: false,
				transferDate: '',
				transferClassLabel: '',
				transferRemark: '',
				currentTeacher: null,
				transferRecords: [], // 存储调课记录
			}
		},
		created() {
			this.selectedDate = this.getToday();
			this.getClassList()
		},
		methods: {
			 async getClassList() {
			    try {
			      // 1. 同步获取存储中的 userId
			      const { data: userId } = await uni.getStorage({ key: 'userId' });
						
			      // 2. 赋值到组件实例
			      this.userId = userId;
			      console.log('获取的userId:', userId, this.userId);
			      
			      // 3. 使用获取的userId请求数据
			      const res = await selectClass(userId);
			      console.log('班级列表数据:', res);
			      
			      // 4. 处理返回数据（示例）
			      this.classList = res.data.claList.map(item => {
					  return {
			        label: item.claDescribe,
			        value: item.claId
			      }
				  });
				  this.classList = [this.classList]
			      
			      // 5. 默认选中第一个班级
			      if (this.classList[0] && this.classList[0].length > 0) {
			        this.selectedClass = this.classList[0][0].value;
			        this.selectedClassLabel = this.classList[0][0].label;
			        this.defaultIndex = [0];
			      }
				  console.log(this.classList[0][0].value, 990)
			      
			    } catch (error) {
			      console.error('操作失败:', error);
			      uni.showToast({ title: '数据加载失败', icon: 'none' });
			    }
			  },
			getToday() {
				const d = new Date();
				return `${d.getFullYear()}-${(d.getMonth()+1).toString().padStart(2,'0')}-${d.getDate().toString().padStart(2,'0')}`;
			},
			onClassConfirm(e) {
				const item = e.value[0];
				this.selectedClass = item.value;
				this.selectedClassLabel = item.label;
				this.showClassPicker = false;
				console.log(e.value[0].value,123)
			},
			onDateConfirm(e) {
				// console.log(e, 123)
				this.selectedDate = e[0];
				this.showCalendar = false;
			},
			handleAllCheck(val) {
				const checked = val.length > 0;
				this.teachers.forEach(t => t.status = checked ? 0 : t.status);
			},
			setStatus(teacher, status) {
				if (status === 3) {
					// 如果是调课状态，打开调课弹窗
					this.currentTeacher = teacher;
					// 查找该教师的调课记录
					const transferRecord = this.transferRecords.find(record => record.teacherId === teacher.id);
					if (transferRecord) {
						// 如果有记录，回显数据
						this.transferDate = transferRecord.transferDate;
						this.transferClassLabel = transferRecord.toClass;
						this.transferRemark = transferRecord.remark;
					} else {
						// 如果没有记录，清空数据
						this.transferDate = '';
						this.transferClassLabel = '';
						this.transferRemark = '';
					}
					this.showTransferPopup = true;
				} else if (teacher.status === 3) {
					// 如果当前是调课状态，切换到其他状态时提示
					uni.showModal({
						title: '提示',
						content: '是否删除调课记录？',
						success: (res) => {
							if (res.confirm) {
								// 删除调课记录
								this.transferRecords = this.transferRecords.filter(
									record => record.teacherId !== teacher.id
								);
								teacher.status = status;
							}
						}
					});
				} else {
					teacher.status = status;
				}
			},
			closeTransferPopup() {
				this.showTransferPopup = false;
				this.transferDate = '';
				this.transferClassLabel = '';
				this.transferRemark = '';
			},
			onTransferDateConfirm(e) {
				this.transferDate = e[0];
				this.showTransferDatePicker = false;
			},
			onTransferClassConfirm(e) {
				this.transferClassLabel = e.value[0].label;
				// console.log(e.value[0].value.value, 789)
				console.log(1)
				this.showTransferClassPicker = false;
			},
			submitTransfer() {
				if (!this.transferDate || !this.transferClassLabel) {
					uni.showToast({
						title: '请选择调课时间和班级',
						icon: 'none'
					});
					return;
				}

				// 添加调课记录
				this.transferRecords.push({
					teacherId: this.currentTeacher.id,
					teacherName: this.currentTeacher.name,
					fromClass: this.selectedClassLabel,
					toClass: this.transferClassLabel,
					transferDate: this.transferDate,
					remark: this.transferRemark
				});

				// 设置教师状态为调课
				this.currentTeacher.status = 3;

				// 关闭弹窗
				this.closeTransferPopup();

				uni.showToast({
					title: '调课成功',
					icon: 'success'
				});
			},
			submitAttendance() {
				const attendanceData = this.teachers.map(teacher => ({
					id: teacher.id,
					name: teacher.name,
					status: teacher.status,
					statusText: ['出勤', '缺勤', '请假', '调课'][teacher.status]
				}));

				console.log('考勤数据：', attendanceData);
				console.log('调课记录：', this.transferRecords);

				uni.showToast({
					title: '考勤已提交',
					icon: 'success'
				});
			}
		}
	}
</script>

<style scoped>
	.submit-btn {
		width: 40%;
		padding-left: 10px;
		margin-left: 20px;
	}

	.attendance-page {
		background: #f5f5f5;
		min-height: 100vh;
	}

	.top-bar {
		display: flex;
		align-items: center;
		padding: 80rpx 16rpx;
		background: #2563eb;
	}

	.teacher-avatar {
		width: 150rpx;
		height: 150rpx;
		border-radius: 50%;
		margin: auto auto;
		margin-right: 80rpx;
	}

	.progress {
		margin-left: 84rpx;
		font-size: 24rpx;
	}

	.action-bar {
		display: flex;
		align-items: center;
		padding: 16rpx;
		background: #fff;
		padding-left: 76rpx;
	}

	.teacher-list {
		display: flex;
		flex-wrap: wrap;
		background: #fff;
	}

	.teacher-item {
		width: 33%;
		text-align: center;
		padding: 16rpx 0;
	}

	.avatar {
		width: 90rpx;
		height: 90rpx;
		border-radius: 50%;
		float: left;
		margin-left: 20px;
	}

	.name {
		float: left;
		margin-left: 10px;
		margin-top: 10px;
	}

	.tag {
		background: #e53e3e;
		color: #fff;
	}

	.picker-btn {
		background: #fff;
		color: #333;
		padding: 8rpx 30rpx 8rpx 16rpx;
		/* 右侧增加空间放箭头 */
		border-radius: 8rpx;
		margin: 0 60rpx;
		min-width: 120rpx;
		text-align: center;
		position: relative;
		/* 为箭头定位做准备 */
		border: 1px solid #dcdfe6;
		/* 添加边框 */
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		/* 轻微阴影增加立体感 */
		display: inline-flex;
		align-items: center;
		justify-content: center;
	}

	/* 向上箭头样式 */
	.arrow-up {
		position: absolute;
		right: 10rpx;
		/* 距离右侧10rpx */
		top: 50%;
		transform: translateY(-50%);
		width: 0;
		height: 0;
		border-left: 8rpx solid transparent;
		border-right: 8rpx solid transparent;
		border-bottom: 12rpx solid #999;
		/* 使用border创建三角形 */
		transition: all 0.3s;
	}

	/* 日历打开时箭头旋转效果（可选） */
	.picker-btn.active .arrow-up {
		transform: translateY(-50%) rotate(180deg);
		border-bottom-color: #2563eb;
	}

	.status-box {
		display: flex;
		flex-direction: column;
		gap: 10rpx;
		margin: 90rpx 0;
		align-items: center;
	}

	.status-row {
		display: flex;
		flex-direction: row;
		gap: 10rpx;
		justify-content: center;
	}

	.status-item {
		width: 80rpx;
		height: 60rpx;
		line-height: 60rpx;
		text-align: center;
		border: 2rpx solid #ddd;
		border-radius: 8rpx;
		font-size: 24rpx;
		transition: all 0.3s;
	}

	.status-item:nth-child(1).active {
		background-color: #2563eb;
		color: #fff;
		border-color: #2563eb;
	}

	.status-item:nth-child(2).active {
		background-color: #eab308;
		color: #fff;
		border-color: #eab308;
	}

	.status-item:nth-child(3).active {
		background-color: #22c55e;
		color: #fff;
		border-color: #22c55e;
	}

	.status-item:nth-child(4).active {
		background-color: #ef4444;
		color: #fff;
		border-color: #ef4444;
	}

	/* 第二排的状态选项样式 */
	.status-row:nth-child(2) .status-item:nth-child(1).active {
		background-color: #22c55e;
		color: #fff;
		border-color: #22c55e;
	}

	.status-row:nth-child(2) .status-item:nth-child(2).active {
		background-color: #ef4444;
		color: #fff;
		border-color: #ef4444;
	}

	.class-section {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
	}

	.progress {
		margin-top: 10rpx;
		color: #fff;
		font-size: 24rpx;
	}

	.u-popup[data-v-52d4ddd1] {
		flex: 1;
		display: none;
	}

	.transfer-popup {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		width: 600rpx;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
	}

	.transfer-header {
		text-align: center;
		margin-bottom: 30rpx;
		padding-bottom: 20rpx;
		border-bottom: 1px solid #f0f0f0;
	}

	.transfer-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 8rpx;
	}

	.transfer-subtitle {
		font-size: 24rpx;
		color: #999;
	}

	.transfer-form {
		margin-bottom: 30rpx;
	}

	.form-item {
		margin-bottom: 24rpx;
		display: flex;
		align-items: flex-start;
	}

	.form-label {
		display: flex;
		align-items: center;
		width: 160rpx;
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
	}

	.label-icon {
		margin-right: 8rpx;
		font-size: 24rpx;
	}

	.form-value {
		flex: 1;
		margin-left: 16rpx;
		font-size: 28rpx;
		color: #666;
		padding: 8rpx 0;
	}

	.form-input {
		flex: 1;
		margin-left: 16rpx;
	}

	.transfer-buttons {
		display: flex;
		justify-content: space-between;
		gap: 20rpx;
		margin-top: 20rpx;
	}

	.cancel-btn {
		flex: 1;
		background: #f5f5f5;
		color: #666;
		border: 1px solid #ddd;
	}

	.submit-btn {
		flex: 1;
		background: #2563eb;
		color: #fff;
	}

	.transfer-picker {
		flex: 1;
		background: #f8f9fa;
		color: #333;
		padding: 16rpx 20rpx;
		border-radius: 8rpx;
		margin-left: 16rpx;
		min-width: 200rpx;
		text-align: left;
		position: relative;
		border: 1px solid #e9ecef;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		display: flex;
		align-items: center;
		justify-content: space-between;
		transition: all 0.3s ease;
	}

	.transfer-picker:active {
		background: #e9ecef;
		transform: scale(0.98);
	}

	.picker-arrow {
		font-size: 20rpx;
		color: #999;
		transition: all 0.3s ease;
	}

	.transfer-picker.active .picker-arrow {
		transform: rotate(180deg);
		color: #2563eb;
	}
</style>